import { Route, Router } from "react-router";
import { isValidElement } from 'react';
import { Provider } from 'mobx-react';
import DataView from "../components/data";
import AppDesigner from "../components/designer";
import BoardWidgetEditor from "../components/designer/analysis/BoardWidgetEditor";
import DataBoardWidget from "../components/designer/analysis/DataBoardWidget";
import FormPreview from "../components/designer/form/preview";
import { ExcelPage, TaskView } from '../components/task'
import ExcelTemplateView from "../components/excel-template/TemplateView";
import Home from '../components/Home';
import { WeaLocaleProvider } from 'ecCom';
import API from '../apis/task';


const getLabel = WeaLocaleProvider.getLabel;

const getLocaleLabel = WeaLocaleProvider.getLocaleLabel.bind(this, 'edc');

// export default (
//     <Route path="edc" onEnter={getLocaleLabel} component={Home} >
//         <Route path='designer/:appid' component={AppDesigner} />
//         <Route path='widget/chart/:actionType(/:id)' component={BoardWidgetEditor} />
//         <Route path='form/preview/:appid' component={FormPreview} />
//         <Route path='view' component={TaskView} />
//         <Route path='excel' component={ExcelPage} />
//         <Route path='data' component={DataView} />
//         <Route path='dataBoard' component={DataBoardWidget} />
//         <Route path='exceltemplate/view' component={ExcelTemplateView} />
//         <Route path='noRight' component={() => <div style={{ textAlign: "center", paddingTop: 100, color: '#ccc', fontSize: 24 }}>
//             <i className="icon-coms-locking"></i>
//             <div style={{ fontSize: 16 }}>{getLabel('503347', '没有权限')}</div>
//         </div>} />
//     </Route>
// );


const routes = {
    path: 'edc',
    component: Home,
    onEnter: getLocaleLabel,
    childRoutes: [
        {
            path: 'view',
            component: TaskView,
            getChildRoutes({ location: { query,pathname } }, cb) {
                if (pathname.indexOf('/edc/view/') !== -1) {
                    new Promise(r => {
                        const getResource = () => {
                            API.getLoadResource({ ...query }).then(result => {
                                if (result.config) {
                                    const { module: moduleName, staticResource = '' } = result.config;
                                    if (!loadjs.isDefined(moduleName)) {
                                        loadjs(staticResource.split(","), moduleName, {
                                            success: () => {
                                                if (window[moduleName]) {
                                                    const routes = transRoute(window[moduleName]);
                                                    let routeArr = [];
                                                    if (Array.isArray(routes)) {
                                                        routeArr.concat(routes)
                                                    } else if (typeof routes === 'object') {
                                                        routeArr.push(routes)
                                                    }
                                                    r(routeArr);
                                                }
                                            }
                                        });
                                    } else {
                                        if (window[moduleName]) {
                                            const routes = transRoute(window[moduleName]);
                                            let routeArr = [];
                                            if (Array.isArray(routes)) {
                                                routeArr.concat(routes)
                                            } else if (typeof routes === 'object') {
                                                routeArr.push(routes)
                                            }
                                            r(routeArr);
                                        }
                                    }
                                }


                            })
                        }
                        getResource();
                    }).then(routeArr => {
                        cb(null, routeArr);
                    })
                }else {
                    cb(null,[])
                }

            }
        },
        { path: 'designer/:appid', component: AppDesigner },
        { path: 'widget/chart/:actionType(/:id)', component: BoardWidgetEditor },
        { path: 'form/preview/:appid', component: FormPreview },
        { path: 'excel', component: ExcelPage },
        { path: 'data', component: DataView },
        { path: 'dataBoard', component: DataBoardWidget },
        { path: 'exceltemplate/view', component: ExcelTemplateView },
        {
            path: 'noRight', component: () => {
                <div style={{ textAlign: "center", paddingTop: 100, color: '#ccc', fontSize: 24 }}>
                    <i className="icon-coms-locking"></i>
                    <div style={{ fontSize: 16 }}>{getLabel('503347', '没有权限')}</div>
                </div>
            }
        }
    ],
}

function transRoute(mod) {
    const { Route, store } = mod;
    const hasStore = store && Object.keys(store).length > 0;
    const loop = r => {
        let childRoutes = [];
        if (Array.isArray(r)) {
            // child: Array
            return r.map(l => loop(l));
        } else if (isValidElement(r)) {
            // child: React.Element
            if (Array.isArray(r.props.children)) {
                r.props.children.forEach(c => {
                    if (Array.isArray(c)) {
                        childRoutes = childRoutes.concat(loop(c));
                    } else {
                        childRoutes.push(loop(c));
                    }
                });
            } else if (typeof r.props.children === 'object') {
                childRoutes = [loop(r.props.children)];
            }
            // filter child not Route
            childRoutes = childRoutes.filter(Boolean);
            // IndexRoute
            const childIndexRoute = childRoutes.filter(c => c.type === 'IndexRoute');
            // IndexRedirect
            const childIndexRedirect = childRoutes.filter(c => c.type === 'IndexRedirect');
            // Route
            childRoutes = childRoutes.filter(c => c.type === 'Route');
            // return
            const newProps = { ...r.props };
            const type = r.type.displayName;
            delete newProps.children;
            return {
                ...newProps,
                ...(hasStore && r.props.component ? {
                    component: props => (
                        <Provider ecId={`${this && this.props && this.props.ecId || ''}_Provider@hjxevs`} {...store}>
                            <r.props.component ecId={`${this && this.props && this.props.ecId || ''}_component@b24hx3`} {...props} />
                        </Provider>
                    ),
                } : {}),
                childRoutes,
                type,
                ...(childIndexRoute.length === 1 ? {
                    indexRoute: childIndexRoute[0],
                } : {}),
                ...(childIndexRedirect.length === 1 ? {
                    indexRoute: {
                        onEnter: (nextState, replace) => {
                            const { location: { basename, pathname, search } } = nextState;
                            const { to } = childIndexRedirect[0];
                            if (to.indexOf('/') === 0) return replace(to);
                            return replace(`${basename}${pathname}/${to}${search}`)
                        }
                    },
                } : {}),
            };
        }
    };
    if (Array.isArray(Route)) {
        return Route.map(r => loop(r));
    } else if (isValidElement(Route)) {
        return loop(Route);
    }
    return null;
}

export default <Router ecId={`${this && this.props && this.props.ecId || ''}_Router@8zh47z`} {...routes} />